﻿namespace Algoritmia.Problems.RegularExpressions
{
    public class ThompsonAutomatonBuilder
    {
        private NFASet _nfaSet;

        public NFASet.Nfa Build(RegExpTree tree)
        {
            _nfaSet = new NFASet();
            return PrivateBuild(tree);
        }

        private NFASet.Nfa PrivateBuild(RegExpTree tree)
        {
            if ( tree.Literal.Equals("*") )
            {
                return PrivateBuild(tree.Left).Close();
            }
            if ( tree.Literal.Equals("·"))
            {
                return PrivateBuild(tree.Left).Concat(PrivateBuild(tree.Right));
            }
            if ( tree.Literal.Equals("|"))
            {
                return PrivateBuild(tree.Left).Union(PrivateBuild(tree.Right));
            }
            else
            {
                var nfa = _nfaSet.CreateNfa();
                nfa.AddTransition(nfa.Start, tree.Literal, nfa.End);
                return nfa;
            }
        }

    }
}
